package org.loofer.ext.utils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

public class MultiHashMap<K, V> implements Serializable {
    private static final long serialVersionUID = 2309170850883325510L;
    private final HashMap<K, HashMap<V, V>> backedMap = new HashMap();

    public V get(K key, V value) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        return map == null ? null : map.get(value);
    }

    public Collection<V> get(K key) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        return map == null ? null : map.values();
    }

    public V put(K key, V value) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        if (map == null) {
            map = new HashMap();
            this.backedMap.put(key, map);
        }
        return map.put(value, value);
    }

    public void put(K key, Collection<V> values) {
        if (values != null) {
            HashMap<V, V> map = (HashMap) this.backedMap.get(key);
            if (map == null) {
                map = new HashMap();
                this.backedMap.put(key, map);
            }
            for (V value : values) {
                map.put(value, value);
            }
        }
    }

    public V remove(K key, V value) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        return map == null ? null : map.remove(value);
    }

    public Collection<V> remove(K key) {
        HashMap<V, V> map = (HashMap) this.backedMap.remove(key);
        return map == null ? null : map.values();
    }

    public boolean contains(K key, V value) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        return map != null && map.containsKey(value);
    }

    public boolean contains(K key) {
        return this.backedMap.containsKey(key);
    }

    public void clear() {
        this.backedMap.clear();
    }

    public boolean isEmpty() {
        return this.backedMap.isEmpty();
    }

    public int sizeOf(K key) {
        HashMap<V, V> map = (HashMap) this.backedMap.get(key);
        return map == null ? 0 : map.size();
    }

    public int size() {
        int size = 0;
        for (HashMap<V, V> map : this.backedMap.values()) {
            size += map.size();
        }
        return size;
    }

    public Set<K> keySet() {
        return this.backedMap.keySet();
    }
}
